using Microsoft.AspNetCore.Mvc;
using MyMvcSoft.Repository;
using MyMvcSoft.Models;
using System.Linq;
using MyMvcSoft.RepuestParams;
namespace MyMvcSoft.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            var CategoryRep = new EfRepository<Category>();
            var Category = CategoryRep.Table.FirstOrDefault();
            if (Category == null)
            {
                CategoryRep.Insert
                (new Category
                {
                    CategoryName = "美女"
                });
            }


            var ProductRep = new EfRepository<Product>();
            var Product = ProductRep.Table.Where(x => x.IsDeleted == false).ToList();
            return View(Product);
        }


        public IActionResult CreateOrEdit(int id)
        {
            if (id > 0)
            {

                var ProductRep = new EfRepository<Product>();
                var Product = ProductRep.Table.Where(x => x.Id == id).FirstOrDefault<Product>();
                return View(Product);
            }
            else
            {
                var ProductRep = new EfRepository<Product>();
                var Product = ProductRep.Table.Where(x => x.Id == 0).FirstOrDefault<Product>();

                return View(Product);
            }
        }
            public IActionResult Save(ProductParams request)
        {
            var ProductRep = new EfRepository<Product>();
            if (request.Id > 0)
            {
                var entity = ProductRep.Table.Where(x => x.Id == request.Id).FirstOrDefault();
                entity.ProductName = request.ProductName;
                entity.Supplier=request.Supplier;
                entity.Price=request.Price;
                entity.Stock=request.Stock;
                entity.Remarks = request.Remarks;
                ProductRep.Update(entity);
            }
            else
            {
                ProductRep.Insert
                (
                    new Product
                    {
                        ProductName = request.ProductName.Trim(),
                        Supplier = request.Supplier.Trim(),
                        Price = request.Price,
                        Stock=request.Stock,
                        Remarks = request.Remarks.Trim(),
                        CategoryId = 1
                    }
                );
            }
            return Ok();
            }

            public IActionResult Query()
        {
                return View();
        }

         public IActionResult Delete(int id)
        {
            var ProductRep = new EfRepository<Product>();
            ProductRep.Delete(id);
            return RedirectToAction("Index");
        }

    }
}
